package com.success.task.web.servlet.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.success.task.web.utils.StringUtil;

@Controller
public class Download {
	
	@RequestMapping("download.go")
	public void downloadFile (HttpServletRequest request, HttpServletResponse response) {
        String fileName = request.getParameter("fileName");
        String fileUrl = request.getParameter("fileUrl");
        if(null != fileName) {
	        try {
	        	fileName = new String(fileName.getBytes("ISO8859_1"),"UTF-8");
			} catch (UnsupportedEncodingException e2) {
				String extensionName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				fileName = new StringBuffer("下载文件").append(extensionName).toString();
			}
			fileName = fileName.replaceAll(" ", "");
	        try {  
	            File file=new File(StringUtil.getString(StringUtil.decodeString(StringUtil.decodeString(fileUrl))));  
	            InputStream inputStream=new FileInputStream(file);  
	            try {
	            	response.reset();
		        	response.setContentType( "application/x-octetstream;charset=ISO8859_1"); 
		            response.setContentType("multipart/form-data");  
					response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("GBK"),"ISO8859_1"));
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
	            OutputStream os=response.getOutputStream();  
	            byte[] b=new byte[1024];  
	            int length;  
	            while((length=inputStream.read(b))>0){  
	                os.write(b,0,length);  
	            }  
	            inputStream.close();  
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
        } else {
        	return;
        }
	}
}
